package com.nbjtjc.safe.config;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.crypto.SecureUtil;
import com.nbjtjc.safe.mapper.sys.SysPermissionMapper;
import com.nbjtjc.safe.mapper.sys.SysRoleMapper;
import com.nbjtjc.safe.mapper.sys.SysUserMapper;
import com.nbjtjc.safe.mapper.sys.SysUserRoleMapper;
import com.nbjtjc.safe.model.sys.SysPermission;
import com.nbjtjc.safe.model.sys.SysRole;
import com.nbjtjc.safe.model.sys.SysUser;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * shiro 登录时候验证，subject.login调用的就是这个类的方法
 */
@Component
public class UserRealm extends AuthorizingRealm {

    @Autowired
    private SysPermissionMapper sysPermissionMapper;

    @Autowired
    private SysRoleMapper sysRoleMapper;

    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    /**
     * 这里主要获取用户的权限
     * @param principal
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principal) {
        SysUser user = (SysUser) principal.getPrimaryPrincipal();
        Integer userId = user.getUserId();
        Set<String> roles = new HashSet<>();
        List<String> permsList = new ArrayList<>();
        if (userId == 1) {
            List<SysPermission> permissions = sysPermissionMapper.selectAll();
            if (permissions != null) {
                permissions.forEach(permission -> {
                    permsList.add(permission.getPerms());
                });
            }
            List<SysRole> roleList = sysRoleMapper.selectAll();
            if(!ArrayUtil.isEmpty(roleList)){
                roleList.forEach(role -> {
                    roles.add(role.getRole());
                });
            }
        } else {
            List<String> roleList = sysUserRoleMapper.findRoleByUserId(userId);
            roles.addAll(roleList);
            List<String> perms = sysPermissionMapper.findPermissionByUserId(userId);
            if (perms != null) {
                permsList.addAll(perms);
            }
        }
        //用户权限列表
        Set<String> permsSet = new HashSet<String>();
        for (String perms : permsList) {
            if (StringUtils.isBlank(perms)) {
                continue;
            }
            permsSet.addAll(Arrays.asList(perms.trim().split(",")));
        }
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.setStringPermissions(permsSet);
        info.setRoles(roles);
        return info;
    }

    /**
     * 验证密码是否正确
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        String pwd = new String(token.getPassword());
        System.out.println(SecureUtil.md5(pwd));
        SysUser user=sysUserMapper.find(new String(token.getUsername()),pwd);
        if (user == null) {
            throw new UnknownAccountException("用户不存在");
        }
        SecurityUtils.getSubject().getSession().setAttribute("user",user);
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, new String(" "), user.getUsername());
        return info;
    }

    @Override
    public void setCredentialsMatcher(CredentialsMatcher credentialsMatcher) {
        CustomCredentialsMatcher customCredentialsMatcher = new CustomCredentialsMatcher();
        super.setCredentialsMatcher(customCredentialsMatcher);
    }
}
